package com.weavernorth.action.breastFeeding;


import com.weavernorth.util.Logger4jUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.workflow.webservices.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.weavernorth.util.MyCommonUtils.getUseridByCode;
import static com.weavernorth.util.dateUtils.getEveryday;

public class BreastFeeding extends BaseCronJob {
//    public static Log log = LogFactory.getLog(BreastFeeding.class.getName());
    Logger log = Logger4jUtil.getLoggerByName("/Timmer/BreastFeeding/");
    private String gh;
    private String userId;
    private String beginDates;
    private String endDates;
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getGh() {
        return gh;
    }

    public void setGh(String gh) {
        this.gh = gh;
    }

    public String getBeginDates() {
        return beginDates;
    }

    public void setBeginDates(String beginDates) {
        this.beginDates = beginDates;
    }

    public String getEndDates() {
        return endDates;
    }

    public void setEndDates(String endDates) {
        this.endDates = endDates;
    }

    //创建哺乳假
    @Override
    public void execute() {
        log.info("----哺乳假定时创建流程任务执行开始----：");
        //格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前日期
        Date date = new Date();

        String beginDate = (beginDates==null)?sdf.format(date):beginDates;
        log.info("开始日期：" + beginDate);
        String endDate = (endDates==null)?sdf.format(date):endDates;
        log.info("结束日期：" + endDate);
        String strUserid="";
        if(gh!=null){
            strUserid=getUseridByCode(gh);
        }
        if(userId!=null){
            strUserid=userId;
        }
        //得到当前日期是否为工作日
        // boolean bleFlag = getIsWorkday(formatDate);
        breastExecute(beginDate,endDate,strUserid);
        log.info("----哺乳假定时创建流程任务执行结束----：");
    }
    public String breastExecute(String beginDate,String endDate,String strUserid){
        String strResult="哺乳假流程生成成功！";
        BaseBean bb = new BaseBean();
        //获取日期段内每一天的日期
        List<String> everyday = getEveryday(beginDate, endDate);
        for (String dates : everyday) {
            RecordSet rsBr = new RecordSet();
            //查询哺乳假登记流程流转的建模表中数据
            String strBrSql = " select  up.djr, up.djrbm,up.ksrq,up.jsrq,up.xzxjsj,up.sfdbt,up.hzsl,kq.workbegintime,kq.workendtime  from  uf_ppbrjdjb up,kq_format_detail kq where up.djr=kq.resourceid and kq.workbegindate is not null and workenddate is not null and kq.kqdate='"+dates+"'";
            if(!"".equals(strUserid)){
                strBrSql+=" and up.djr='"+strUserid+"'";
            }
            log.info("生成哺乳假的sql:"+strBrSql);
            rsBr.executeQuery(strBrSql);

            //循环创建多条流程
            while (rsBr.next()) {
                //获取登记人
                String strDjr = Util.null2String(rsBr.getString("djr"));
                //登记人部门
                String strBm = Util.null2String(rsBr.getString("djrbm"));
                //开始日期
                String strKsrq = Util.null2String(rsBr.getString("ksrq"));
                //结束日期
                String strJsrq = Util.null2String(rsBr.getString("jsrq"));
                //工作开始时间
                String strWorkBeginTime=Util.null2String(rsBr.getString("workbegintime"));
                //工作结束时间
                String strEndTime=Util.null2String(rsBr.getString("workendtime"));
                //当前日期在哺乳假的登记日期中
                if (strKsrq.compareTo(dates) <= 0 && strJsrq.compareTo(dates) >= 0) {
                    //获取休假时间
                    String strXjsj = Util.null2String(rsBr.getString("xzxjsj"));
                    //获取是否多胞胎
                    String strDbt = Util.null2String(rsBr.getString("sfdbt"));
                    //孩子数量
                    String strHzsl = Util.null2String(rsBr.getString("hzsl"));

                    //创建流程的主表
                    //存放主表字段的数组
                    WorkflowRequestTableField[] wrti = new WorkflowRequestTableField[10];
                    //添加姓名字段
                    log.info("姓名：" + strDjr);
                    wrti[0] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[0].setFieldName("resourceId");
                    //赋值
                    wrti[0].setFieldValue(Util.null2String(strDjr));
                    wrti[0].setView(true);
                    wrti[0].setEdit(true);
                    wrti[0].setFieldOrder(0);
                    wrti[0].setMand(false);

                    //添加部门字段
                    log.info("部门：" + strBm);
                    wrti[1] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[1].setFieldName("departmentId");
                    //赋值
                    wrti[1].setFieldValue(Util.null2String(strBm));
                    wrti[1].setView(true);
                    wrti[1].setEdit(true);
                    wrti[1].setFieldOrder(0);
                    wrti[1].setMand(false);

                    //添加请假类型字段：默认为哺乳假(12)
                    log.info("请假类型：");
                    wrti[2] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[2].setFieldName("newLeaveType");
                    //赋值
                    wrti[2].setFieldValue(Util.null2String("12"));
                    wrti[2].setView(true);
                    wrti[2].setEdit(true);
                    wrti[2].setFieldOrder(0);
                    wrti[2].setMand(false);

                    //添加开始日期字段
                    log.info("开始日期：" + dates);
                    wrti[3] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[3].setFieldName("fromDate");
                    //赋值
                    wrti[3].setFieldValue(dates);
                    wrti[3].setView(true);
                    wrti[3].setEdit(true);
                    wrti[3].setFieldOrder(0);
                    wrti[3].setMand(false);

                    //添加结束日期字段
                    log.info("结束日期：" + dates);
                    wrti[4] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[4].setFieldName("toDate");
                    //赋值
                    wrti[4].setFieldValue(dates);
                    wrti[4].setView(true);
                    wrti[4].setEdit(true);
                    wrti[4].setFieldOrder(0);
                    wrti[4].setMand(false);

                    //判断休假时间段
                    //上午
                    //获取时间
                    int intHour = (Integer.parseInt(strHzsl) +1) * 30;
                    if (strXjsj.equals("0")) {
                        //添加开始时间字段
                        log.info("开始时间："+strWorkBeginTime);
                        wrti[5] = new WorkflowRequestTableField();
                        //字段在数据库中的字段名
                        wrti[5].setFieldName("fromTime");
                        //赋值
                        wrti[5].setFieldValue(Util.null2String(strWorkBeginTime));
                        wrti[5].setView(true);
                        wrti[5].setEdit(true);
                        wrti[5].setFieldOrder(0);
                        wrti[5].setMand(false);

                        //拼接日期
                        //String strRqSj = strEndDate;
                        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
                        Date date2=new Date();
                        try {
                            date2 = dateFormat.parse(strWorkBeginTime);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Date expireTime = new Date(date2.getTime() + intHour*60*1000);
                        String newTime = dateFormat.format(expireTime);
                        //添加结束时间字段
                        log.info("结束时间："+newTime);
                        wrti[6] = new WorkflowRequestTableField();
                        //字段在数据库中的字段名
                        wrti[6].setFieldName("toTime");
                        //赋值
                        wrti[6].setFieldValue(Util.null2String(newTime));
                        wrti[6].setView(true);
                        wrti[6].setEdit(true);
                        wrti[6].setFieldOrder(0);
                        wrti[6].setMand(false);

                    }
                    //下午
                    else {
                        //拼接日期
                        // String strRqSj = strEndDate;
                        log.info("时间：" + strEndTime);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
                        Date date2=new Date();
                        try {
                            date2 = dateFormat.parse(strEndTime);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Date expireTime = new Date(date2.getTime() - intHour*60*1000);
                        String newTime = dateFormat.format(expireTime);

                        log.info("加上时间后的时间:" + newTime);
                        //添加开始时间字段
                        log.info("开始时间："+newTime);
                        wrti[5] = new WorkflowRequestTableField();
                        //字段在数据库中的字段名
                        wrti[5].setFieldName("fromTime");
                        //赋值
                        wrti[5].setFieldValue(Util.null2String(newTime));
                        wrti[5].setView(true);
                        wrti[5].setEdit(true);
                        wrti[5].setFieldOrder(0);
                        wrti[5].setMand(false);

                        //添加结束时间字段
                        log.info("结束时间："+strEndTime);
                        wrti[6] = new WorkflowRequestTableField();
                        //字段在数据库中的字段名
                        wrti[6].setFieldName("toTime");
                        //赋值
                        wrti[6].setFieldValue(Util.null2String(strEndTime));
                        wrti[6].setView(true);
                        wrti[6].setEdit(true);
                        wrti[6].setFieldOrder(0);
                        wrti[6].setMand(false);
                    }
                    //添加时长字段
                    //获取时长（小时计算）
                    Double douSj =(Double.parseDouble(String.valueOf(intHour)) / Double.parseDouble("60"));
                    log.info("时长：" + douSj);
                    wrti[7] = new WorkflowRequestTableField();
                    //字段在数据库中的字段名
                    wrti[7].setFieldName("duration");
                    //赋值
                    wrti[7].setFieldValue(Util.null2String(douSj));
                    wrti[7].setView(true);
                    wrti[7].setEdit(true);
                    wrti[7].setFieldOrder(0);
                    wrti[7].setMand(false);


                    WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];
                    wrtri[0] = new WorkflowRequestTableRecord();
                    wrtri[0].setWorkflowRequestTableFields(wrti);
                    WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();
                    wmi.setRequestRecords(wrtri);


                    //基本信息
                    WorkflowBaseInfo wbi = new WorkflowBaseInfo();
                    //流程的workflowid
                    String strBreast=Util.null2String(bb.getPropValue("humanMess","breastWorkflowid"));
                    log.info("哺乳假流程id:"+strBreast);
                    wbi.setWorkflowId(strBreast);


                    WorkflowRequestInfo wri = new WorkflowRequestInfo();
                    //创建人
                    wri.setCreatorId(strDjr);
                    //紧急程度
                    wri.setRequestLevel("0");
                    //请求的名称
                    wri.setRequestName("哺乳假申请流程");


                    //主表数据
                    wri.setWorkflowMainTableInfo(wmi);
                    wri.setWorkflowBaseInfo(wbi);

                    WorkflowServiceImpl wfsi = new WorkflowServiceImpl();
                    try {
                        String strRequestid = wfsi.doCreateWorkflowRequest(wri, Integer.parseInt(strDjr));
                        log.info("生成流程的requestid:" + strRequestid);
                    } catch (Exception e) {
                        log.info("异常捕获=" + e);
                        strResult="生成流程失败,失败原因："+e.toString();
                        break;
                    }
                }
            }
        }
        return strResult;
    }

    //判断是否为工作日
    public boolean getIsWorkday(String strDate) {
        boolean ret = true;

        //如果为公众假日，则不为工作日
        String sql = "select 1 from HrmPubHoliday where holidayDate = '" + strDate + "' and changeType = 1 and countryid = 1 ";
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        if (rs.getCounts() > 0) {
            ret = false;
        }
        //如果为周末,默认为非工作日且被调配为工作日，则返回false
        int intDay = getWeekByDate(strDate);
        log.info("是否为周末==" + intDay);
        if (intDay == 1 || intDay == 7) {
            //如果为公众假日，则不为工作日
            String sql2 = "select 1 from HrmPubHoliday where holidayDate = '" + strDate + "' and changeType = 2 and countryid = 1 ";
            RecordSet rs1 = new RecordSet();
            rs1.execute(sql2);
            if (rs1.getCounts() > 0) {
                ret = true;
            } else {
                ret = false;
            }
        }

        log.info("返回结果==" + ret);
        return ret;

    }

    //获取周末数字
    public int getWeekByDate(String strDate) {
        int returnStr = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            Date date = sdf.parse(strDate);
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(date);
            returnStr = calendar.get(Calendar.DAY_OF_WEEK);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnStr;
    }





}
